<template>
    <van-nav-bar title="购物车" left-text="返回" left-arrow @click-left="() => { $router.push('/') }" />
    <!-- 没数据 -->
    <div v-if="!usercarts.length">
        <van-empty image="error" description="描述文字" />
    </div>
    <!-- 有数据 -->
    <div v-else>
        <van-swipe-cell v-for="item in usercarts">
            <van-card :price="item.goods.goods_price" :title="item.goods.goods_name" class="goods-card"
                thumb="https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg">
                <template #thumb>
                    <van-checkbox v-model="item.checked"></van-checkbox>
                    <img style="height: 100px;width: 100px;" :src="item.goods.goods_big_logo" alt="">
                </template>
                <template #num>
                    <van-stepper v-model="item.number" theme="round" button-size="22" disable-input />
                </template>
            </van-card>
            <template #right>
                <van-button square text="删除" type="danger" @click="delcart(item.id)" style="height: 100%;"
                    class="delete-button" />
            </template>
        </van-swipe-cell>
    </div>
    <van-submit-bar :price="priceAll" button-text="提交订单" @submit="onSubmit" @click="onSubmit">
        <van-checkbox v-model="checkedAll">全选</van-checkbox>
        <template #tip>
            你的收货地址不支持配送, <span @click="onClickLink">修改地址</span>
        </template>
    </van-submit-bar>
</template>

<script setup>
import { ref, computed } from 'vue'
let usercarts = ref([])
import { useCounterStore } from '@/stores/cart.js'
const stores = useCounterStore()
const data = () => {
    let username = localStorage.getItem('username')
    usercarts.value = stores.cart.filter(item => item.username == username)
}
data()
const delcart = (id) => {
    stores.delCart(id)
    data()
}
const checkedAll=computed({
    get(){
        if(usercarts.value.length==0){
            return false
        }
        else{
            return usercarts.value.every(item =>item.checked)
        }
    },
    set(val){
        return usercarts.value.forEach(item => item.checked=val)
    }
})
const priceAll=computed(()=>{
    let priceAll=0
    let cartok=usercarts.value.filter(item=> item.checked)
    cartok.forEach(item=>{
        priceAll+=item .number*item.goods.goods_price
    })
    return priceAll*100
})

import {payApi} from '@/api/api'
const onSubmit=()=>{
    console.log(priceAll.value)
    payApi(priceAll.value).then(res=>{
        window.open(res.data.data,'_blank')
    })
}
</script>

<style lang="scss" scoped></style>